package com.chenqi.authentication.code;

import com.chenqi.authentication.CustomAuthenticationFailureHandler;
import com.chenqi.controller.CustomLoginController;
import com.chenqi.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: 自定义验证码过滤器(在所有过滤器之前执行)
 * @program: ardai-securtiy-parent
 * @author: ChenQi
 * @create: 2021-03-2021/3/17-16-47
 */
@Slf4j
@Component("imageCodeValidateFilter")
public class ImageCodeValidateFilter extends OncePerRequestFilter {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (securityProperties.getAuthentication().getLoginProcessingUrl().equals(request.getRequestURI()) && request.getMethod().equalsIgnoreCase("post")) {
            //校验验证码的合法性
            try {
                validate(request);
            } catch (AuthenticationException e) {
                customAuthenticationFailureHandler.onAuthenticationFailure(request,response,e);
                //一定要记得结束
                return;
            }
        }
        //拦截器链进行放行
        filterChain.doFilter(request,response);

    }

        private void validate(HttpServletRequest request) throws ValidateCodeException {
            //1.拿到session里面的code
            String sessionCode =(String) request.getSession().getAttribute(CustomLoginController.SESSION_KEY);
            //2.获取用户输入的code
            String inputCode = request.getParameter("code");
            log.info("输入的验证码:",inputCode);
            //3.如果输入的验证码为空抛出异常
            if(StringUtils.isBlank(inputCode)){
                throw new ValidateCodeException("验证码不存在");
            }
            if(!inputCode.equalsIgnoreCase(sessionCode)){
                throw new ValidateCodeException("验证码输入错误");
            }
        }
}
